//
//  TestImage.swift
//  skincare
//
//  Created by whu125 on 2023/5/24.
//

import SwiftUI

import SwiftUI

struct TestImage: View {
    let urls = ["https://fun-skincare.oss-cn-shanghai.aliyuncs.com/2023/05/10/1683720550924719?Expires=1999080550&OSSAccessKeyId=LTAI5tBKaWzQZ8MRhTiD6Ubh&Signature=WimgMRWWBBEH%2F8HvqlYgzgQnrtU%3D", "https://fun-skincare.oss-cn-shanghai.aliyuncs.com/2023/05/10/1683720514463845?Expires=1999080513&OSSAccessKeyId=LTAI5tBKaWzQZ8MRhTiD6Ubh&Signature=%2FTuZ%2FfaVkQq2olKjNvKSKTgEqd0%3D"] // 使用您的URL

    struct ImageWithURL: Hashable {
        let image: Image
        let url: String

        func hash(into hasher: inout Hasher) {
            hasher.combine(url)
        }

        static func ==(lhs: ImageWithURL, rhs: ImageWithURL) -> Bool {
            return lhs.url == rhs.url
        }
    }

    @State var images: [ImageWithURL] = [] // 存储图像数组
    @State var count = 0 // 计数器

    var body: some View {
        VStack {
            if images.isEmpty {
                ProgressView()
            } else {
                TabView {
                    ForEach(images, id: \.self) { image in
                        image.image
                            .resizable()
                            .scaledToFit()
                    }
                }
            }
        }
        .onAppear {
            loadImage()
        }
    }

    func loadImage() {
        guard count < urls.count else {
            return
        }
        guard let url = URL(string: urls[count]) else {
            count += 1
            return
        }
        URLSession.shared.dataTask(with: url) { data, _, error in
            if let error = error {
                print("Error: \(error.localizedDescription)")
                return
            }
            if let data = data, let uiImage = UIImage(data: data) {
                DispatchQueue.main.async {
                    images.append(ImageWithURL(image: Image(uiImage: uiImage), url: urls[count]))
                    count += 1
                    loadImage()
                }
            }
        }
        .resume()
    }
}




struct TestImage_Previews: PreviewProvider {
    static var previews: some View {
        TestImage()
    }
}
